import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:starfish_tenement_app/component/smart_refresh/smart_refresh_widget.dart';
import 'package:starfish_tenement_app/pages/news/news_detail/news_detail_page.dart';
import 'package:starfish_tenement_app/route/route_path.dart';
import 'package:starfish_tenement_app/route/route_utils.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import '../../../api/models/app_news_data.dart';
import '../../../component/app_bar/app_title_bar.dart';
import '../../../component/new_card/news_card_item.dart';
import '../../../component/styles/app_colors.dart';
import '../../../utils/string_utils.dart';
import 'news_type_vm.dart';

///资讯分类页面
class NewsTypePage extends StatefulWidget {
  const NewsTypePage({super.key});

  @override
  State createState() {
    return _NewsTypePageState();
  }
}

class _NewsTypePageState extends State<NewsTypePage>
    with SingleTickerProviderStateMixin {
  final NewsTypeViewModel _viewModel = NewsTypeViewModel();
  late TabController tabController;

  ///RefreshController需要和SmartRefreshWidget一一对应
  final List<RefreshController> _refreshControllers =
      List.generate(3, (generator) {
    return RefreshController(initialRefresh: false);
  });

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: 3, vsync: this);
    _viewModel.getNewsTypeList();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (context) {
          return _viewModel;
        },
        child: Scaffold(
            backgroundColor: Colors.white,
            body: SafeArea(
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                  //咨询标题
                  AppTitleBar(
                      title: "资讯",
                      onBackTap: () {
                        RouteUtils.pushForNamed(
                            context, RoutePath.newsListPage);
                      },
                      onRightTap: () {}),
                  //tabBar
                  _tabBarView(),
                  //tab页面
                  _tabPagesView()
                ]))));
  }

  Widget _tabBarView() {
    return SizedBox(
        width: double.infinity,
        child: TabBar(
            controller: tabController,
            isScrollable: true,
            labelColor: AppColors.textColor20,
            indicator: const BoxDecoration(),
            indicatorColor: Colors.transparent,
            indicatorSize: TabBarIndicatorSize.tab,
            labelStyle: TextStyle(
                fontSize: 24.sp,
                color: AppColors.textColor20,
                fontWeight: FontWeight.w600),
            unselectedLabelStyle:
                TextStyle(fontSize: 17.sp, color: AppColors.textColor8B),
            tabs: const [
              Tab(text: "雷区"),
              Tab(text: "行情"),
              Tab(text: "科普"),
            ]));
  }

  Widget _tabPagesView() {
    return Expanded(
        child: Padding(
            padding: EdgeInsets.only(left: 17.w, right: 14.w),
            child: TabBarView(controller: tabController, children: [
              _tabPageView(0),
              _tabPageView(1),
              _tabPageView(2)
            ])));
  }

  Widget _tabPageView(int tabIndex) {
    return Consumer<NewsTypeViewModel>(
      builder: (context, vm, child) {
        if (tabIndex == 0) {
          return _typeListView(tabIndex, listData: vm.mineFieldList);
        } else if (tabIndex == 1) {
          return _typeListView(tabIndex, listData: vm.marketList);
        } else {
          return _typeListView(tabIndex, listData: vm.scienceList);
        }
      },
    );
  }

  Widget _typeListView(
    int tabIndex, {
    List<AppNewsItemData>? listData,
  }) {
    return Scaffold(
      backgroundColor: AppColors.whiteColor80,
      body: SmartRefreshWidget(
        controller: _refreshControllers[tabIndex],
        footer: _footer(tabIndex),
        onLoading: () {
          _onLoadMore(tabIndex);
        },
        onRefresh: () {
          _onRefresh(tabIndex);
        },
        child: WaterfallFlow.builder(
          padding: EdgeInsets.only(top: 10.sp),
          gridDelegate:
              const SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 5.0,
            mainAxisSpacing: 5.0,
          ),
          itemCount: listData?.length,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              margin: EdgeInsets.all(2.h),
              child: Center(
                child: NewsCardItem(
                  newsCardType: NewsCardType.circle,
                  coverImageUrl:
                      StringUtils.takeStrForList(listData?[index].imageList),
                  content: listData?[index].subtitle ?? "",
                  avatarUrl:
                      StringUtils.takeStrForList(listData?[index].imageList),
                  nickname: "不吃香菜",
                  createTime: "2025-05-24",
                  onTap: () {
                    print("onTap");
                    RouteUtils.pushForNamed(context, RoutePath.newsDetailPage,
                        arguments: {"newsId": listData?[index].id});
                  },
                  likeTap: () {
                    print("likeTap");
                  },
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _footer(index) {
    return CustomFooter(
      builder: (context, mode) {
        Widget body;
        if (_refreshControllers[index].footerStatus == LoadStatus.idle) {
          //闲置状态
          body = const Text("没有更多数据了");
        } else if (_refreshControllers[index].footerStatus ==
            LoadStatus.loading) {
          //加载状态
          body = const Text("正在努力加载中...");
        } else if (_refreshControllers[index].footerStatus ==
            LoadStatus.failed) {
          //加载数据失败
          body = const Text("加载失败，稍后重试");
        } else {
          //没有数据
          body = const Text("没有更多数据了");
        }
        return SizedBox(
          height: 50.h,
          child: Center(child: body),
        );
      },
    );
  }

  ///刷新
  void _onRefresh(index) async {
    await Future.delayed(const Duration(milliseconds: 800));
    _refreshControllers[index].refreshCompleted();
  }

  ///加载更多
  void _onLoadMore(index) async {
    await Future.delayed(const Duration(milliseconds: 500));
    //数据加载
    if (mounted) {
      setState(() {});
    }
    _refreshControllers[index].loadComplete();
  }
}
